package com.smh;

import org.junit.jupiter.api.Test;

/**
 * @author shiminghui
 * @date 2025/3/17 17:36
 * @description: TODO
 */
public class _062_CatalanTree {


    @Test
    public void test1() {
        System.out.println(catalan2(5));
    }

    /**
     * 求Catalan数列的第n项
     */
    public int catalan(int n) {
        int res = dg(n, new int[n + 1]);
        return res;
    }

    public int dg(int n, int[] dp) {
        if (n == 0 || n == 1) {
            return 1;
        }
        if (dp[n] != 0) {
            return dp[n];
        }
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += dg(i, dp) * dg(n - i - 1, dp);
        }
        dp[n] = res;
        return res;
    }


    public int catalan2(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }

        int[] dp = new int[n + 1];
        dp[0] = dp[1] = 1;
        for (int i = 2; i < dp.length; i++) {
            for (int j = 0; j < i; j++) {
                dp[i] += dp[j] * dp[i - j - 1];
            }
        }
        return dp[n];
    }

}
